package com.lz.blog.service.impl;

import com.lz.blog.dao.mapper.TagMapper;
import com.lz.blog.dao.pojo.Tag;
import com.lz.blog.service.TagService;
import com.lz.blog.vo.Result;
import com.lz.blog.vo.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Resource
    private TagMapper tagMapper;

    @Override
    public List<TagVo> findTagsByArticleId(Long articleId) {
        //mybatis-plus无法进行多表查询
        List<Tag> tags = tagMapper.findTagsByArticleId(articleId);
        return copyList(tags);
    }

    public TagVo copy(Tag tag){
        TagVo tagVo = new TagVo();
        BeanUtils.copyProperties(tag,tagVo);
        return tagVo;
    }

    public List<TagVo> copyList(List<Tag> tagList){
        List<TagVo> tagVoList = new ArrayList<>();
        for (Tag tag : tagList) {
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }


    @Override
    public Result hot(int limit) {
        /**
         * 1.标签所拥有的文章数量最多，就是最热标签
         * 2.查询  根据tag_id分组计数，从大到小排列， 取前limit个
         */
        List<Long> tagIds = tagMapper.findHotsTagIds(limit);

        if(CollectionUtils.isEmpty(tagIds)){
            return Result.success(Collections.emptyList());
        }
        //需求的是tag_id与tag_name
        //select * from tag where id in (1,2,3,4)  在in中的条件不能为空，因此要进行一个判断
        List<Tag> tagList = tagMapper.findTagByTagIds(tagIds);
        return Result.success(tagList);
    }

}
